package services;

import tw.edu.tku.im.maze.DeliveryListenerI;
import tw.edu.tku.im.maze.LeaveRoomDeliverer;
import tw.edu.tku.im.maze.LeaveRoomRep;
import tw.edu.tku.im.maze.LeaveRoomReq;
import tw.edu.tku.im.maze.RepPacket;
import tw.edu.tku.im.maze.TimeOutRep;

import com.example.maze.ConnectionInfo;

import android.app.IntentService;
import android.content.Intent;

public class LeaveRoomService extends IntentService 
                               implements DeliveryListenerI{

   public LeaveRoomService()            { super("RemoveRoomService"); }
   public LeaveRoomService(String name) { super(name); }

   @Override
   protected void onHandleIntent(Intent intent) {
      try{
//android.util.Log.d("DebugMsg","catched");
         LeaveRoomDeliverer mLeaveRoomDeliverer= new LeaveRoomDeliverer();
         mLeaveRoomDeliverer.deliver( new LeaveRoomReq( ConnectionInfo.roomId, 
                                                        ConnectionInfo.id, 
                                                        ConnectionInfo.ticket), 
                                      this );
      } catch(Exception e) {}
   }

   // -------------------------------------------------- 
   @Override
   public void processReply(RepPacket rep) {
      /*do nothing*/
      LeaveRoomRep mLeaveRoomRep= (LeaveRoomRep)rep;
      if(rep instanceof TimeOutRep) {
         android.util.Log.d("DebugMsg", "timeout");
         this.onHandleIntent(new Intent()); // re-connection
      } else {
         if(((LeaveRoomRep)rep).getState() == 0) {
            android.util.Log.d("DebugMsg", "伺服端收到成功離開");
         } else {
            android.util.Log.d("DebugMsg", "發生其他例外");
         }          
      }
   }
}
